﻿// -------------------------------------------------------------------------
//    @FileName         :    NFOnlineAccMgr.cpp
//    @Author           :    gaoyi
//    @Date             :    2025-04-03
//    @Email			:    445267987@qq.com
//    @Module           :    NFOnlineAccMgr
//
// -------------------------------------------------------------------------

#include "NFOnlineAccMgr.h"

#include <NFOnlineAcc.h>

NFOnlineAccMgr::NFOnlineAccMgr()
{
    if (NFShmMgr::Instance()->GetCreateMode() == EN_OBJ_MODE_INIT)
    {
        CreateInit();
    }
    else
    {
        ResumeInit();
    }
}

NFOnlineAccMgr::~NFOnlineAccMgr()
{
}

int NFOnlineAccMgr::CreateInit()
{
    return 0;
}

int NFOnlineAccMgr::ResumeInit()
{
    return 0;
}

NFOnlineAcc* NFOnlineAccMgr::CreateOnlineAcc(uint32_t zoneId, uint64_t uin)
{
    auto pAcc = FindOnlineAcc(zoneId, uin);
    if (pAcc)
    {
        return pAcc;
    }

    CHECK_EXPR(m_accMap.size() < m_accMap.max_size(), nullptr, "m_accMap space not enough zoneId:{} uin:{}", zoneId, uin);
    pAcc = NFOnlineAcc::CreateObj();
    CHECK_NULL_RE_NULL(uin, pAcc, "NFOnlineAcc CreateObj Failed, used num:{} all num:{}, zoneId:{} uin:{}", NFOnlineAcc::GetStaticUsedCount(), NFOnlineAcc::GetStaticItemCount(), zoneId, uin);

    tagAccountAndID acc;
    acc.m_iZoneID = zoneId;
    acc.m_ullUid = uin;
    m_accMap[acc] = pAcc->GetGlobalId();
    pAcc->SetZoneId(zoneId);
    pAcc->SetUid(uin);

    LOG_INFO(0, "Add OnlineAcc zoneId:{} uin:{}", pAcc->GetZoneId(), pAcc->GetUid());
    return pAcc;
}

NFOnlineAcc* NFOnlineAccMgr::FindOnlineAcc(uint32_t zoneId, uint64_t uin)
{
    tagAccountAndID acc;
    acc.m_iZoneID = zoneId;
    acc.m_ullUid = uin;
    auto iter = m_accMap.find(acc);
    if (iter != m_accMap.end())
    {
        int globalId = iter->second;
        return NFOnlineAcc::GetObjByGlobalId(globalId);
    }
    return nullptr;
}

int NFOnlineAccMgr::RemoveOnlineAcc(NFOnlineAcc* pAcc)
{
    CHECK_NULL(0, pAcc);
    tagAccountAndID acc;
    acc.m_iZoneID = pAcc->GetZoneId();
    acc.m_ullUid = pAcc->GetUid();
    m_accMap.erase(acc);

    LOG_INFO(0, "Remove OnlineAcc zoneId:{} uin:{}", pAcc->GetZoneId(), pAcc->GetUid());
    NFOnlineAcc::DestroyObj(pAcc);
    return 0;
}

int NFOnlineAccMgr::TryDeleteOnlineAcc(NFOnlineAcc* pAcc, int logicSvrId, uint64_t roleId)
{
    CHECK_NULL(roleId, pAcc);
    pAcc->ClearOnlineData(logicSvrId, roleId);

    if (!pAcc->CanDelete())
    {
        LOG_INFO(roleId, "OnlineAcc Not Delete, Has Role Online or In Lock Time, zoneId:{} uin:{}", pAcc->GetZoneId(), pAcc->GetUid());
        return 0;
    }

    pAcc->SetState(ONLINE_ACC_EXIT);

    RemoveOnlineAcc(pAcc);

    return 0;
}
